<template>
  <view class="container">
    <!-- 设备选择下拉框 -->
<view class="device-selector">
  <picker mode="selector" :range="deviced_ids" @change="handleDeviceChange" :value="currentDeviceIndex" :disabled="deviced_ids.length === 0">
    <view class="picker" :class="{ 'picker-disabled': deviced_ids.length === 0 }">
      <text v-if="deviced_ids.length > 0">当前设备: {{ current_deviced_id }}</text>
      <text v-else class="picker-empty">暂无绑定的设备</text>
      <text class="picker-arrow" v-if="deviced_ids.length > 0">▼</text>
    </view>
  </picker>
</view>

    <!-- 设备连接状态 -->
    <view class="device-status">
      <text class="device-name">已选择设备: {{ current_deviced_id }}</text>
      <text class="connection-status">{{ current_deviced_id ? 'MQTT状态: 已连接' : 'MQTT状态: 未连接' }}</text>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-grid">

      <view class="menu-item" @click="publishMessage('UP')">
        <text class="menu-icon">📹</text>
        <text class="menu-text">上升</text>
      </view>

      <view class="menu-item" @click="publishMessage('DOWN')">
        <text class="menu-icon">📱</text>
        <text class="menu-text">下降</text>
      </view>

      <view class="menu-item" @click="publishMessage('CAPTURE')">
        <text class="menu-icon">📷</text>
        <text class="menu-text">采集图片</text>
      </view>

      <view class="menu-item" @click="publishMessage('VIDEO')">
        <text class="menu-icon">📱</text>
        <text class="menu-text">拍摄视频</text>
      </view>
    </view>

    <!-- 操作记录显示区域 -->
    <view class="message-container">
      <scroll-view scroll-y="true" class="message-scroll">
        <view v-for="(log, index) in operationLogs" :key="index" class="log-item">
          <text class="log-time">{{ log.time }}</text>
          <text class="log-content">{{ log.content }}</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
  import {
    get_user_devicedId,
    deviced_up,
    deviced_camera
  } from "../../api/device_control";

  import request from '../../utils/request'
  import {
    createAuthHeader
  } from '../../utils/request'


  export default {
    data() {
      return {

        current_deviced_id: '', // 设置默认值
        deviced_ids: [],
        currentDeviceIndex: 0,
        is_up: true,
        is_down: false,
        isloading: false,
        operationLogs: [] // 操作记录数组
      }
    },

    onLoad() {
      this.get_user_devicedId()
      this.has_decives()
    },

    onTabItemTap() {
      this.get_user_devicedId()
            this.has_decives()
    },

    methods: {
      // 获取当前时间
      getCurrentTime() {
        const now = new Date();
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
        const seconds = now.getSeconds().toString().padStart(2, '0');
        return `${hours}:${minutes}:${seconds}`;
      },

      //获取用户设备列表
      async get_user_devicedId() {
        const result = await get_user_devicedId()
        if (result.message === 'ok') {
          this.deviced_ids = result.data.map(device => device.id)
        }
        console.log(result.data)
      },
      
      //是否有绑定的设备
      has_decives(){
        // 添加设备检查 - 点击时才弹出提示
        if (this.deviced_ids.length === 0) {
          uni.showModal({
            title: '提示',
            content: '暂无绑定的设备，请先绑定设备后再进行操作',
            showCancel: false,
            confirmText: '知道了'
          });
          return;
        }
      },

      // 添加操作记录
      addOperationLog(content) {
        this.operationLogs.unshift({
          time: this.getCurrentTime(),
          content: content
        });
        // 限制最多显示100条记录
        if (this.operationLogs.length > 100) {
          this.operationLogs.pop();
        }
      },

      // 设备选择变化
      handleDeviceChange(e) {
        this.currentDeviceIndex = e.detail.value;
        this.current_deviced_id = this.deviced_ids[this.currentDeviceIndex];
        this.addOperationLog(`切换设备为: ${this.current_deviced_id}`);
      },


      async publishMessage(command) {
        let operationName = '';
        if (this.current_deviced_id === '') return uni.$showMsg('请先选择设备！');
        switch (command) {
          //上升
          case 'UP':
            if (this.is_up) {
              return uni.$showMsg('设备已处上升！')
            }
            const upRes = await deviced_up(this.current_deviced_id, 1)
            if (upRes) {
              this.is_down = false
              this.is_up = true
              operationName = '设备上升操作';
              break;
            }
            uni.$showMsg('操作失败！')
            break

            //下降
          case 'DOWN':
            if (this.is_down) {
              return uni.$showMsg('设备已处下降！')
            }
            const downRes = await deviced_up(this.current_deviced_id, 1)
            if (downRes) {
              this.is_down = true
              this.is_up = false
              operationName = '设备下降操作';
              break;
            }
            uni.$showMsg('操作失败！')
            break

            //拍照
          case 'CAPTURE':
            const CAPTURE_Res = await deviced_camera(this.current_deviced_id)
            if (CAPTURE_Res) {
              operationName = '设备拍照操作';
              break;
            }
            uni.$showMsg('操作失败！')
            break

          case 'VIDEO':
            operationName = '设备录制操作';
            console.log('111')
            break;

          default:
            operationName = '未知操作';
        }


        this.addOperationLog(`执行: ${operationName}`);

        // 显示操作反馈
        uni.showToast({
          title: operationName,
          icon: 'success'
        });
      }
    },
    created() {
      // 初始化时添加一条欢迎日志
      this.addOperationLog('系统初始化完成');
    }
  }
</script>


<style lang="scss">
  .container {
    padding: 30rpx;
    min-height: 100vh;
    background: #f5f5f5;
    display: flex;
    flex-direction: column;
  }

  .device-selector {
    margin-bottom: 20rpx;

    .picker {
      background: white;
      padding: 20rpx;
      border-radius: 10rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

      .picker-arrow {
        color: #999;
        font-size: 24rpx;
      }
    }
  }

  .menu-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 30rpx;
    margin: 40rpx 0;
  }

  .menu-item {
    background: white;
    border-radius: 20rpx;
    padding: 40rpx 20rpx;
    text-align: center;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    transition: all 0.3s;
    position: relative;
  }

  .menu-item:active {
    transform: scale(0.95);
    background: #f8f8f8;
  }

  .menu-icon {
    font-size: 60rpx;
    margin-bottom: 20rpx;
    display: block;
  }

  .menu-text {
    font-size: 28rpx;
    color: #333;
    display: block;
  }

  .device-status {
    padding: 20rpx;
    background: #f0f8f4;
    border-radius: 10rpx;
    border-left: 4rpx solid #1b9a7c;
    margin-bottom: 20rpx;
  }

  .device-name {
    display: block;
    font-size: 26rpx;
    color: #333;
    margin-bottom: 5rpx;
  }

  .connection-status {
    display: block;
    font-size: 22rpx;
    color: #666;
  }

  .message-container {
    flex: 1;
    background: #fff;
    border-radius: 10rpx;
    padding: 15rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    min-height: 450rpx;
    max-height: 600rpx;
  }

  .message-scroll {
    flex: 1;
    overflow-y: auto;
  }

  .log-item {
    padding: 15rpx 0;
    border-bottom: 1rpx solid #eee;
    display: flex;
    align-items: center;
    font-size: 26rpx;
  }

  .log-time {
    color: #999;
    margin-right: 20rpx;
    min-width: 140rpx;
    font-size: 24rpx;
  }

  .log-content {
    color: #333;
    flex: 1;
    word-break: break-all;
  }
</style>